﻿Imports System.IO
Imports System.Drawing.Imaging
Imports Mysoft.Map.Extensions.Json
Imports System.Text

Public Class ClipManager
    Private ReadOnly _mPics As New Dictionary(Of String, Image)
    Private ReadOnly _mTextData As New TextData
    Private _pageIndex As Integer = 0
    Private _txtIndex As Integer = 0
    Public Event ReTop()
    Public Event StopTop()
    ''' <summary>
    ''' 这个是主控件
    ''' </summary>
    ''' <remarks></remarks>
    Private ReadOnly _tabctl As TabControl
    Public Sub New(ByVal tabCtl As TabControl)
        '初始化：控件绑定
        _tabctl = tabCtl
    End Sub
    Public Sub AddText()
        AddText("文本剪辑" & Format(_txtIndex, "00"), Clipboard.GetText())
    End Sub

    Private Sub AddText(ByVal Title As String, ByVal Content As String)
        '初始化序号字符串
        Dim txtName As String = "txt" & Format(_txtIndex, "00")
        '创建页签
        _tabctl.TabPages.Add(txtName, Title)
        '插入带有Fill模式dock的文本框（多行，双滚动条，填满父窗口，初始文本为空）
        Dim txtControl As New TextBox
        txtControl.Text = Content
        txtControl.Multiline = True
        txtControl.ScrollBars = ScrollBars.Both
        txtControl.Dock = DockStyle.Fill
        txtControl.Focus()
        txtControl.Name = "txtCtl" & Format(_txtIndex, "00")
        AddHandler txtControl.Click, AddressOf MouseClick
        AddHandler txtControl.LostFocus, AddressOf LostFocus
        Dim page As TabPage = _tabctl.TabPages.Item(txtName)
        page.Controls.Add(txtControl)
        page.ImageKey = "txt.png"
        '聚焦到当前页签
        _tabctl.SelectedIndex = page.TabIndex
        '序号加
        _txtIndex += 1
    End Sub

    Public Sub AddImage(ByVal img As Image)
        '图片与当前的图片相同，不更新
        If img Is Nothing Then
            Exit Sub
        End If

        Dim picName As String = "pic" & _pageIndex.ToString()
        For Each valuePair As KeyValuePair(Of String, Image) In _mPics
            If valuePair.Value Is Nothing Then
                picName = valuePair.Key
                _mPics.Item(picName) = img
                Exit For
            End If
            If IsImgSame(img, valuePair.Value) Then
                Exit Sub
            End If
        Next
        '图片与当前图片不同,开始新增图片:
        '1、增加一个到缓存
        If Not _mPics.ContainsKey(picName) Then
            _mPics.Add(picName, img)
        End If
        '2、增加一个page
        _tabctl.TabPages.Add(picName, "截图 " & Format(_pageIndex, "00"))
        '3、增加截图到page上
        Dim page As TabPage = _tabctl.TabPages.Item(picName)
        Dim panel As New Panel
        Dim picBox As New PictureBox()
        panel.AutoScroll = True
        panel.Dock = DockStyle.Fill
        picBox.Image = img
        picBox.SizeMode = PictureBoxSizeMode.AutoSize
        panel.Controls.Add(picBox)
        page.Controls.Add(panel)
        page.ImageKey = "bmp.png"
        '4、切换到当前
        _tabctl.SelectedIndex = page.TabIndex
        _pageIndex += 1
        '   如果图片都不相同，就新增一个标签，标签名称为
    End Sub

    Public Function IsImgSame(ByRef aImg As Image, ByRef bImg As Image) As Boolean
        If aImg Is Nothing AndAlso bImg Is Nothing Then
            Return True
        End If
        If aImg Is Nothing OrElse bImg Is Nothing Then
            Return False
        End If
        Using ms1 As New MemoryStream, ms2 As New MemoryStream
            aImg.Save(ms1, ImageFormat.Bmp)
            bImg.Save(ms2, ImageFormat.Bmp)
            If ms1.Length <> ms2.Length Then
                Return False
            Else
                Dim aBytes() As Byte = ms1.GetBuffer()
                Dim bBytes() As Byte = ms2.GetBuffer()
                For i As Integer = 0 To aBytes.Length - 1
                    If aBytes(i) <> bBytes(i) Then
                        Return False
                    End If
                Next
                Return True
            End If
        End Using
    End Function
    '文本输入时特殊处理
    Public Sub MouseClick(ByVal sender As Object, ByVal e As Windows.Forms.MouseEventArgs)
        RaiseEvent StopTop()
    End Sub

    Public Sub LostFocus(ByVal sender As Object, ByVal e As EventArgs)
        RaiseEvent ReTop()
    End Sub
#Region "数据备份-还原"
    Public Sub SaveDataToJson()
        '遍历收集tab页中的数据
        Dim ctl As Control
        For Each page As TabPage In _tabctl.TabPages
            ctl = page.Controls.Item(0)
            If TypeName(ctl) = "TextBox" Then
                _mTextData.Add(page.Text, ctl.Text)
            End If
        Next
        '记录当前选中项
        _mTextData.LastSelectedIndex = _tabctl.SelectedIndex
        '保存到文件
        SunSoftUtility.TextProcessing.WriteToFile("tmp.dat", JsonHelper.JsonSerialize(_mTextData))
    End Sub
    Public Sub RestoreDataFromFile()
        '判断tmp.dat文件是否存在
        Dim tmpTextData As TextData
        If Not File.Exists("tmp.dat") Then
            Dim WelMsg As New StringBuilder
            Const Spaces As String = "    "
            With WelMsg
                .AppendLine("欢迎使用ClipHolder v1.9版本")
                .AppendLine("大家可能会用到的内容")
                .AppendFormat("{1}剪贴板：{1}", Spaces, vbCrLf)
                .AppendLine("----------------------------------------")
                .AppendLine(Clipboard.GetText())
                .AppendLine("----------------------------------------")
                .AppendFormat("{0}使用手册：{0}", vbCrLf)
                .AppendFormat("{1}{0}Alt+H：隐藏窗口/显示窗口{1}", Spaces, vbCrLf)
                .AppendFormat("{1}{0}截图：使用QQ截图后，所截的图片会立即显示到一个新的页签中{1}", Spaces, vbCrLf)
                .AppendFormat("{1}{0}文字：点击【新文本签】按钮，可以在新增的文本页签中输入暂存内容{1}", Spaces, vbCrLf)
                .AppendFormat("{1}{0}重命名页签：鼠标右键单击页签{1}", Spaces, vbCrLf)
                .AppendFormat("{1}{0}关闭页签：双击页签{1}", Spaces, vbCrLf)
            End With
            AddText("欢迎使用", WelMsg.ToString())
            Exit Sub
        End If
        '尝试读取文件文本，转换为json数据
        tmpTextData = JsonHelper.JsonDeserialize(Of TextData)(SunSoftUtility.TextProcessing.ReadFile("tmp.dat"))
        '校验完整性
        If tmpTextData._DataBook.Count > 0 Then
            '遍历json List，将每个文本数据恢复
            For Each noteData As TextData.NoteData In tmpTextData.ReleaseList()
                AddText(noteData.Title, noteData.Content)
            Next
        End If
        '恢复默认选中项
        If tmpTextData.LastSelectedIndex >= 0 Then
            _tabctl.SelectedIndex = tmpTextData.LastSelectedIndex
        End If
    End Sub
#End Region
End Class